package apitalkroommine;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class Server {
    private ServerSocket serverSocket;
    //private List<PrintWriter> allOut = new ArrayList<>();
    //key:客户端·昵称   value:客户端的输出流
    private Map<String, PrintWriter> allOut = new HashMap<>();

    public Server() {
        try {
            System.out.println("服务器端启动...");
            serverSocket = new ServerSocket(8088);
            System.out.println("服务器端启动成功...");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            while (true) {
                System.out.println("等待客户端连接...");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端连接成功" + socket.getRemoteSocketAddress());

                ClientHandler handler = new ClientHandler(socket);
                Thread t = new Thread(handler);
                t.start();

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    private class ClientHandler implements Runnable {
        private Socket socket;
        private String host;//记录客户端的ip地址
        private String nickname;//记录客户端的昵称

        public ClientHandler(Socket socket) {
            this.socket = socket;
            //通过socket获取客户端的ip地址
            host = socket.getInetAddress().getHostAddress();
        }

        public void run() {
            PrintWriter pw;
            try {
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader bw = new BufferedReader(isr);

                nickname = bw.readLine();

                OutputStream out = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
                BufferedWriter bw2 = new BufferedWriter(osw);
                pw = new PrintWriter(bw2, true);

                //将对应客户端的输出流存入到共享集合allOut中
                synchronized (allOut) {
//                    allOut.add(pw);
                    allOut.put(nickname, pw);
                }
                sendMessage(nickname + "[" + host + "]上线了，当前人数" + allOut.size());

                String message;
                while ((message = bw.readLine()) != null) {
                    if (message.startsWith("@")) {
                        //发送私聊消息以@开头
                        sendMessageToSome(message);
                    } else {
                        sendMessage(nickname + "[" + host + "]说:" + message);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                synchronized (allOut) {
                    allOut.remove(nickname);
                }
                sendMessage(nickname + "[" + host + "]下线了，当前人数" + allOut.size());
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        public void sendMessage(String message) {
            System.out.println(message);
            synchronized (allOut) {
                for (PrintWriter o : allOut.values()) {
                    o.println(message);
                }
            }
        }

        public void sendMessageToSome(String message) {
            if (message.matches("@.+:.+")) {
                String toNickName = message.substring(1, message.indexOf(":"));
                if (allOut.containsKey(toNickName)){
                    PrintWriter pw = allOut.get(toNickName);
                    String toMessage = message.substring(message.indexOf(":") + 1);
                    pw.println(nickname + "悄悄对你说:" + toMessage);
                }else {
                    PrintWriter pw = allOut.get(nickname);
                    pw.println("该用户不存在");
                }

            }else {
                PrintWriter pw = allOut.get(nickname);
                pw.println("私聊格式错误，格式应当为（@对方昵称:私聊内容）");
            }
        }
    }
}
